import datetime
import re
from flask import Flask,Blueprint,request,jsonify
from database import *
from conf.comm import sqlalchemy_context
import json


#实例化蓝图
bp_course = Blueprint('course',__name__)


#无限极分类
def xtree(data):
    if data:
        tree={}
        list=[]
        #转换成字典
        for i in data:
            tree[i['id']]=i
        #判断是否有父类 =0代表没有父类
        for j in data:
            if j['parent'] == 0:
                list.append(j)
            else:
                #有父类
                #父类下是否有子类 有 append 没有初始化子类
                if 'son' not in tree[j['parent']]:
                    tree[j['parent']]['son'] = []
                #把子类加到特定的父类下
                tree[j['parent']]['son'].append(j)

        return list
    else:
        pass





#添加分类
@bp_course.route('/cartM/',methods=["POST",'GET'])
@sqlalchemy_context()
def cartM():
    if request.method == 'POST':
        data = request.data
        if data:
            data = json.loads(request.data)
        else:
            data = request.form
        cor = Cart(name=data['name'],level=data['level'],params=data['params'])
        db.session.add(cor)
        db.session.commit()
        return jsonify({"code":200})
    else:
        carts = Cart.query.all()
        list = []
        if carts:
            for i in carts:
                dic={'id':i.id,'name':i.name,'level':i.level,'params':i.params,'parent':i.parent}
                list.append(dic)
        list1 = xtree(list)

        return jsonify({"code":200,'list':list1})